import datetime
import logging.config
import os
from ast import literal_eval

from settings import conf

BASE_DIR = conf.BASE_DIR

# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG = literal_eval(conf.DEBUG)
DEBUG = True
ALLOWED_HOSTS = conf.ALLOWED_HOSTS

# ******************* 跨域的配置 ******************* #
# 全部允许配置
# CORS_ORIGIN_ALLOW_ALL = True
# 允许cookie
# CORS_ALLOW_CREDENTIALS = True  # 指明在跨域访问中，后端是否支持对cookie的操作
# 允许任何表头
# CORS_ALLOW_HEADERS = ("*")  # 解决跨域

# 允许的标头
# CORS_ALLOW_HEADERS = (
#     'accept',
#     'accept-encoding',
#     'authorization',
#     'content-type',
#     'dnt',
#     'origin',
#     'user-agent',
#     'x-csrftoken',
#     'x-requested-with',
# )

# # 设置白名单
# CORS_ORIGIN_WHITELIST = ("*")
# # 对应的发送的请求的跨域
# CORS_ALLOW_METHODS = (
#     'DELETE',
#     'GET',
#     'OPTIONS',
#     'PATCH',
#     'POST',
#     'PUT',
#     'VIEW',
# )

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = conf.JWT_SECRET_KEY

# Application definition
INSTALLED_APPS = [
    # 'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'django_redis',
    'corsheaders',  # 注册跨域app
    # 我的app
    'common',
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    # "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "corsheaders.middleware.CorsMiddleware",  # 跨域中间件
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    # "utils.middleware.ApiLoggingMiddleware",
]

ROOT_URLCONF = 'apis.urls'
AUTH_USER_MODEL = 'common.Users'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'wsgi.application'

# Database
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': conf.DB_NAME,
        'USER': conf.DB_USER,
        'PASSWORD': conf.DB_PASSWORD,
        'HOST': conf.DB_HOST,
        'PORT': conf.DB_PORT,
    }

}

CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://{0}:{1}'.format(conf.REDIS_HOST, conf.REDIS_PORT),
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "PASSWORD": "",
        },
    },
}

REST_FRAMEWORK = {
    "DATETIME_FORMAT": "%Y-%m-%d %H:%M:%S",  # 日期时间格式配置
    "DATE_FORMAT": "%Y-%m-%d",
    "DEFAULT_FILTER_BACKENDS": (
        # 'django_filters.rest_framework.DjangoFilterBackend',
        "utils.filters.CustomDjangoFilterBackend",
        "rest_framework.filters.SearchFilter",
        "rest_framework.filters.OrderingFilter",
    ),
    "DEFAULT_PAGINATION_CLASS": "utils.pagination.CustomPagination",  # 自定义分页
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework_simplejwt.authentication.JWTAuthentication",
        "rest_framework.authentication.SessionAuthentication",
    ),
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.IsAuthenticated",  # 只有经过身份认证确定用户身份才能访问
        # 'rest_framework.permissions.IsAdminUser', # is_staff=True才能访问 —— 管理员(员工)权限
        # 'rest_framework.permissions.AllowAny', # 允许所有
        # 'rest_framework.permissions.IsAuthenticatedOrReadOnly', # 有身份 或者 只读访问(self.list,self.retrieve)
    ],
    "EXCEPTION_HANDLER": "utils.exception.CustomExceptionHandler",  # 自定义的异常处理
    "DEFAULT_RENDERER_CLASSES": (
        'rest_framework.renderers.JSONRenderer',
        # 'rest_framework_xml.renderers.XMLRenderer'  # 添加 XML 渲染器
    ),
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.JSONParser',
        # 'rest_framework_xml.parsers.XMLParser',  # 添加 XML 解析器
    ),
}
AUTHENTICATION_BACKENDS = [
    'utils.permission.CustomModelBackend',
]
JWT_EXPIRATION_DAYS = int(conf.JWT_EXPIRATION_DAYS)

SIMPLE_JWT = {
    # token有效时长
    "ACCESS_TOKEN_LIFETIME": datetime.timedelta(days=1, ),
    # token刷新后的有效时间
    "REFRESH_TOKEN_LIFETIME": datetime.timedelta(days=1),
    # 设置前缀
    "AUTH_HEADER_TYPES": ("JWT",),
    "ROTATE_REFRESH_TOKENS": True,
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False

# 日志配置
if not DEBUG:
    LOGGING_CONFIG = None
    logging.config.fileConfig(conf.LOGGING_CONFIG_FILE, disable_existing_loggers=False)

# 静态文件配置
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static')

# 修复为 Redis 配置（Windows 专用）
CELERY_BROKER_URL = "redis://127.0.0.1:6379/0"  # 显式 IPv4 地址
CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379/0"
